package com.iris.netty.review;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BioServer2 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8889);
        ExecutorService executor = Executors.newCachedThreadPool();
        while(true){
            final Socket  socket = serverSocket.accept();
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream input = socket.getInputStream();
                        byte[] bytes = new byte[128];
                        String inputStr = "";
                        int count ;
                        while ((count = input.read(bytes))!=-1){
                            inputStr = new String(bytes,0,count);
                            System.out.println(inputStr);
                            OutputStream out = socket.getOutputStream();
                            out.write("ok".getBytes());
                            if("end1".equals(inputStr)){
                                break;
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    }
}
